<template>
  <el-dialog
    :title="!dataForm.id ? '新增' : '修改'"
    :close-on-click-modal="false"
    :visible.sync="visible"
  >
    <el-form
      :model="dataForm"
      :rules="dataRule"
      ref="dataForm"
      @keyup.enter.native="dataFormSubmit()"
      label-width="120px"
    >
      <el-form-item label="供应商名称" prop="supplierId">
        <el-autocomplete
          class="inline-input"
          v-model="dataForm.supplierId"
          :fetch-suggestions="querySearch"
          placeholder="供应商名称"
          @select="handleSelect"
          :trigger-on-focus="true"
        ></el-autocomplete>
      </el-form-item>
      <el-form-item label="spu干货名" prop="spuName">
        <el-input v-model="dataForm.spuName" placeholder="spu干货名"></el-input>
      </el-form-item>
      <el-form-item label="spu干货图片" prop="spuImg">
        <single-upload v-model="dataForm.spuImg"></single-upload>
      </el-form-item>
    </el-form>
    <span slot="footer" class="dialog-footer">
      <el-button @click="visible = false">取消</el-button>
      <el-button type="primary" @click="dataFormSubmit()">确定</el-button>
    </span>
  </el-dialog>
</template>

<script>
import SingleUpload from "@/components/upload/singleUpload";
//import引入的组件需要注入到对象中才能使用

export default {
  components: {
    SingleUpload
  },
  data() {
    return {
      visible: false,
      dataForm: {
        id: 0,
        supplierId: "",
        spuName: "",
        spuImg: ""
      },
      temp: "",
      suppliers: [],
      supplierNameMap: new Map(),
      supplierIdMap: new Map(),
      dataRule: {
        supplierId: [
          { required: true, message: "供应商名称不能为空", trigger: "blur" }
        ],
        spuName: [
          { required: true, message: "spu干货名不能为空", trigger: "blur" }
        ],
        spuImg: [{ required: true, message: "请上传干货图片", trigger: "blur" }]
      }
    };
  },
  methods: {
    init(id) {
      this.dataForm.id = id || 0;
      this.visible = true;
      this.$nextTick(() => {
        this.$refs["dataForm"].resetFields();
        if (this.dataForm.id) {
          this.$http({
            url: this.$http.adornUrl(
              `/ware/supplierspudetail/info/${this.dataForm.id}`
            ),
            method: "get",
            params: this.$http.adornParams()
          }).then(({ data }) => {
            if (data && data.code === 0) {
              this.dataForm.supplierId = this.supplierIdMap.get(
                data.supplierSpuDetail.supplierId
              );
              this.dataForm.spuName = data.supplierSpuDetail.spuName;
              this.dataForm.spuImg = data.supplierSpuDetail.spuImg;
            }
          });
        }
      });
    },
    // 表单提交
    dataFormSubmit() {
      this.$refs["dataForm"].validate(valid => {
        if (valid) {
          this.$http({
            url: this.$http.adornUrl(
              `/ware/supplierspudetail/${!this.dataForm.id ? "save" : "update"}`
            ),
            method: "post",
            data: this.$http.adornData({
              id: this.dataForm.id || undefined,
              supplierId: this.supplierNameMap.get(this.dataForm.supplierId),
              supplierName: this.dataForm.supplierId,
              spuName: this.dataForm.spuName,
              spuImg: this.dataForm.spuImg
            })
          }).then(({ data }) => {
            if (data && data.code === 0) {
              this.$message({
                message: "操作成功",
                type: "success",
                duration: 1500,
                onClose: () => {
                  this.visible = false;
                  this.$emit("refreshDataList");
                }
              });
            } else {
              this.$message.error(data.msg);
            }
          });
        }
      });
    },
    //下拉列表显示所有的供货商信息
    querySearch(queryString, cb) {
      var suppliers = this.suppliers;
      var results = queryString
        ? suppliers.filter(this.createFilter(queryString))
        : suppliers;
      // 调用 callback 返回建议列表的数据
      console.log(results);
      cb(results);
    },
    createFilter(queryString) {
      return supplier => {
        return (
          supplier.value.toLowerCase().indexOf(queryString.toLowerCase()) === 0
        );
      };
    },
    //查询所有的供货商信息
    searchAllSuppliers() {
      return this.$http({
        url: this.$http.adornUrl("/ware/supplier/get/all/suppliers"),
        method: "get",
        params: this.$http.adornParams({})
      }).then(({ data }) => {
        console.log(data);
        this.suppliers = data.data.map(item => {
          return { value: item.supplierName };
        });
        const nameMap = new Map();
        const idMap = new Map();
        data.data.map(item => {
          var t1 = item.supplierName;
          var t2 = item.id;
          nameMap.set(t1, t2);
          idMap.set(t2, t1);
        });
        this.supplierNameMap = nameMap;
        this.supplierIdMap = idMap;
        console.log(this.supplierIdMap);
      });
    },
    handleSelect(item) {
      console.log(item);
    }
  },
  mounted() {
    this.searchAllSuppliers();
  }
};
</script>
